<template>
  <BottomDialog :is-show="props.isShow">
    <template #prepend-icon>
      <Icon size="16" name="arrowLeft" @click="to(AUTH_ROUTES.CREATE_PASSWORD)"></Icon>
    </template>
    <template #title>
      <p class="text-center text-white font-size-16 font-weight-500 line-height-140 font-style-normal">
        {{ $t('title.finished') }}
      </p>
    </template>
    <template #append-icon>
      <slot name="append-icon"></slot>
    </template>
    <template #body>
      <form action="" class="gap-col-16">
        <GenderPicker v-model="genderPicker.value" :err-msg="genderPicker.error"></GenderPicker>
        <div>
          <InputWrap
            v-model="inputUsername.value"
            :err-msg="inputUsername.error"
            :label="$t('label.username')"
            :placeholder="$t('placeholder.username')"
            :is_lazy="true"
            :append-icon="usernameAppendIcon"
          ></InputWrap>
        </div>
        <v-divider></v-divider>
        <div class="mt-4">
          <div class="d-flex gap-row-16">
            <BlockButton
              :label="$t('common.save')"
              @click="onSaveClicked()"
              :is-gradient="false"
              :disabled="buttonDisabled"
            ></BlockButton>
          </div>
          <div
            v-if="signUpErrMsg"
            class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x"
          >
            {{ signUpErrMsg }}
          </div>
        </div>
      </form>
    </template>
  </BottomDialog>
</template>
<script setup>
import { debounce, join } from 'lodash-es'
import { computed, reactive, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAuthRouteStore } from '@/store/auth-route'
import { usePopupMessageStore } from '@/store/popup-message'
import { useSignUpStore } from '@/store/sign-up'
import { $t } from '@/i18n'
import { useYup, validate } from '@/plugins/yup'
import { checkAccountExist } from '@use/validator'
import BlockButton from '@/components/button/BlockButton.vue'
import BottomDialog from '@/components/dialogs/BottomDialog.vue'
import GenderPicker from '@/components/form/GenderPicker.vue'
import InputWrap from '@/components/form/InputWrap.vue'
import { AUTH_ROUTES, CHECK_ACCOUNT_EXISTS } from '@/constant'
import { trackEvent } from '@/gtm'
import API from '@/http'

const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
})

const { open: openMessage } = usePopupMessageStore()

const signUpStore = useSignUpStore()
const { account, gender, interestedIn, username, password, birthday } = storeToRefs(signUpStore)

const { login } = useAccountStore()

const { to } = useAuthRouteStore()

const genderPicker = reactive({
  value: {},
  error: '',
  check: false,
})

const inputUsername = reactive({
  value: '',
  error: '',
  check: false,
  canUse: true,
})

const usernameAppendIcon = computed(() => {
  if (!inputUsername.value) return ''
  return inputUsername.canUse && inputUsername.check ? 'yesActive' : 'noActive'
})

const signUpErrMsg = ref('')

const yup = useYup()
const schema = yup.object({
  gender: yup.number().required(),
  interestedIn: yup.array().min(1),
})
const usernameSchema = yup
  .string()
  .required()
  .min(4)
  .max(20)
  .matches(/^[a-zA-Z0-9]*$/)

watch(
  () => inputUsername.value,
  debounce(async () => {
    try {
      await validate(usernameSchema, inputUsername).then().catch()
      await checkAccountExist(inputUsername, CHECK_ACCOUNT_EXISTS.USERNAME)
    } catch (e) {
      console.error(`[validate schema] ${e}`)
    }
  }, 200),
)

const buttonDisabled = ref(false)
const onSaveClicked = debounce(
  () => {
    buttonDisabled.value = true
    Promise.all([
      validate(schema, genderPicker),
      validate(usernameSchema, inputUsername),
      checkAccountExist(inputUsername, CHECK_ACCOUNT_EXISTS.USERNAME),
    ])
      .then(() => {
        if (!genderPicker.check || !inputUsername.canUse || !inputUsername.check) return

        username.value = inputUsername.value
        gender.value = genderPicker.value.gender
        interestedIn.value = join(genderPicker.value.interestedIn, ',')

        API.Auth.register({
          data: {
            account: account.value,
            username: username.value,
            password: password.value,
            birthday: birthday.value,
            gender: gender.value,
            interested_in: interestedIn.value,
          },
        })
          .then((response) => {
            console.log('response', response)
            login(response)
            signUpStore.$reset()
            trackEvent({ key: 43 })
            openMessage($t('message.registerSuccess'))
          })
          .catch((err) => {
            console.error(`[auth register] ${err.message}`)
            signUpErrMsg.value = err.message
          })
      })
      .catch((err) => {
        console.error(`[validate schema] ${err}`)
      })
      .finally(() => {
        buttonDisabled.value = false
      })
  },
  2000,
  { leading: true, trailing: false },
)
</script>
